<!DOCTYPE html>






<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">







  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">


















  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">



















































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Android, Java">










<meta name="description" content="哈哈~">
<meta name="keywords" content="zachaxy">
<meta property="og:type" content="website">
<meta property="og:title" content="zachaxy">
<meta property="og:url" content="https://zachaxy.github.io/page/13/index.html">
<meta property="og:site_name" content="zachaxy">
<meta property="og:description" content="哈哈~">
<meta property="og:locale" content="zh-Hans">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="zachaxy">
<meta name="twitter:description" content="哈哈~">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zachaxy.github.io/page/13/">





  <title>zachaxy</title>









</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">






  <div class="container sidebar-position-right
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">


    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zachaxy</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>

        <h1 class="site-subtitle" itemprop="description">纵情向前！</h1>

  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">



    <ul id="menu" class="menu">


        <li class="menu-item menu-item-home">
          <a href="/" rel="section">

              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>

            首页
          </a>
        </li>


        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">

              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>

            标签
          </a>
        </li>


        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">

              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>

            归档
          </a>
        </li>


        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">

              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>

            关于
          </a>
        </li>



        <li class="menu-item menu-item-search">

            <a href="javascript:;" class="popup-trigger">


              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>

            搜索
          </a>
        </li>

    </ul>



    <div class="site-search">

  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>

</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">

  <section id="posts" class="posts-expand">









  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/04/03/RxJava源码详解-基本使用/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/04/03/RxJava源码详解-基本使用/" itemprop="url">RxJava源码详解-基本使用</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-03T09:15:24+08:00">
                2017-04-03
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  2,876
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <h1 id="观察者-VS-被观察者"><a href="#观察者-VS-被观察者" class="headerlink" title="观察者 VS 被观察者"></a>观察者 VS 被观察者</h1><p>以灯泡和开关为例子,这个例子中,开关是被观察者,灯泡是观察者,灯泡观察到开关执行了响应的操作,才执行响应的亮/灭的响应;</p>
<p>被观察者(Observable):事件的产生源头<br>观察者(Observer):事件的处理方;注册感兴趣的事件,一旦事件发生改变,观察者再做出相应的响应</p>
<p>在事件的起点到终点的传递过程中,我们可以进行相应的转换/加工/过滤等操作</p>
<p>在源码中,你可能会看到观察者有时候用Observer,有时候用Subscriber<br>其实:Observer是观察者的接口， Subscriber是实现这个接口的抽象类,<br>因此两个类都可以被当做观察者，由于 Subscriber 在 Observer 的基础上做了一些拓展，加入了新的方法，一般会更加倾向于使用Subscriber。<br><code>abstract class Subscriber&lt;T&gt; implements Observer&lt;T&gt;, Subscription</code></p>
<h1 id="RxJava-的使用"><a href="#RxJava-的使用" class="headerlink" title="RxJava 的使用"></a>RxJava 的使用</h1><h1 id="创建被观察者"><a href="#创建被观察者" class="headerlink" title="创建被观察者"></a>创建被观察者</h1><p>这里分为三种方法:普通模式,偷懒模式1,偷懒模式2</p>
<h2 id="普通模式"><a href="#普通模式" class="headerlink" title="普通模式"></a>普通模式</h2><p>这里分为两种方法:普通模式,偷懒模式1;</p>
<h2 id="订阅"><a href="#订阅" class="headerlink" title="订阅"></a>订阅</h2><p>建立观察者和被观察者的联系<br><code>switcher.subscribe(light);</code></p>
<p>这里可能存在一些疑惑,一般的写法是观察者订阅被观察者,而 RxJava 怎么反过来了<br>是这样的，台灯观察开关，逻辑是没错的，而且正常来看就应该是light.subscribe(switcher)才对，之所以“开关订阅台灯”，是为了保证 <strong>流式API调用风格</strong></p>
<p>注: <strong>当调用订阅操作即调用Observable.subscribe(Observe)方法的时候，被观察者才真正开始发出事件</strong></p>
<h3 id="关于流式API调用风格"><a href="#关于流式API调用风格" class="headerlink" title="关于流式API调用风格"></a>关于流式API调用风格</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">//这就是RxJava的流式API调用</span><br><span class="line">Observable.just(&quot;On&quot;,&quot;Off&quot;,&quot;On&quot;,&quot;On&quot;)</span><br><span class="line">    //在传递过程中对事件进行过滤操作</span><br><span class="line">     .filter(new Func1&lt;String, Boolean&gt;() &#123;</span><br><span class="line">                @Override</span><br><span class="line">                public Boolean call(String s) &#123;</span><br><span class="line">                    return s！=null;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">    .subscribe(mSubscriber);</span><br></pre></td></tr></table></figure>

<p>上面就是一个非常简易的RxJava流式API的调用：同一个调用主体一路调用下来，一气呵成。<br>所以为了保证流式API的调用风格,才用了这种反人类的逻辑;</p>
<p>由于被观察者产生事件，是事件的起点，那么开头就是用Observable这个主体调用来创建被观察者，产生事件，<br>为了保证流式API调用规则，就直接让Observable作为唯一的调用主体，一路调用下去。</p>
<h1 id="操作符"><a href="#操作符" class="headerlink" title="操作符"></a>操作符</h1><p>操作符的分类:</p>
<ul>
<li>转换类操作符:(map flatMap concatMap flatMapIterable switchMap scan groupBy…)；</li>
<li>过滤类操作符:(fileter take takeLast takeUntil distinct distinctUntilChanged skip skipLast …)；</li>
<li>组合类操作符:(merge zip join combineLatest and/when/then switch startSwitch…)。</li>
</ul>
<p>接下来就挑选几个常用的操作符进行讲解:</p>
<h2 id="map"><a href="#map" class="headerlink" title="map"></a>map</h2><p>提供一对一的转换,例如提供的是 url 路径,需要的是对应的 bitmap</p>
<h2 id="flatmap"><a href="#flatmap" class="headerlink" title="flatmap"></a>flatmap</h2><p>将每个Observable产生的事件里的信息再包装成新的Observable传递出来,并且破除的多层嵌套的难题,<br>因为FlatMap可以再次包装新的Observable,而每个Observable都可以使用from(T[])方法来创建自己，这个方法接受一个列表，然后将列表中的数据包装成一系列事件。</p>
<p>还记得创建被观察者时的 from 方法吗,被观察者提供一个数组给 from 方法,被观察者都能将数组中的每个元素转换为被观察者,然后执行观察者的方法.</p>
<p>flatMap 每使用一个 from 方法,就该表一次 for 循环,将一个数组中的元素转换为单个被观察者,仅仅使用from,就该表一层循环,多层嵌套的循环就使用多次from()方法<br>是的代码看起来并没有嵌套的那么复杂,背后的原理就是使用from</p>
<p>所谓 flat就是:我们传入的是一个年级(包含多个班,每个班都多个同学,打印每个同学的姓名),第一步用form已经将年级拆成了多个班,但这不是终极目的,而是在将每个班的每个同学对应过来;回想之前的处理逻辑,每产生一个事件,不等待,直接发出去,但是现在不同,要等一个班的from结束之后(攒齐这个班所有同学,然后再一次发出去),接下来在解析下一个班</p>
<h2 id="concatMap"><a href="#concatMap" class="headerlink" title="concatMap"></a>concatMap</h2><p>concatMap()解决了flatMap()的交叉问题，它能够把发射的值连续在一起.</p>
<h2 id="flatMapIterable"><a href="#flatMapIterable" class="headerlink" title="flatMapIterable"></a>flatMapIterable</h2><p>flatMapIterable()和flatMap()几乎是一样的，不同的是flatMapIterable()它转化的多个Observable是使用Iterable作为源数据的。(示例代码如下)并没有看出来什么区别,还是使用flatmap吧</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Observable.from(communities)</span><br><span class="line">        .flatMapIterable(<span class="keyword">new</span> Func1&lt;Community, Iterable&lt;House&gt;&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Iterable&lt;House&gt; <span class="title">call</span><span class="params">(Community community)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> community.houses;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;)</span><br><span class="line">        .subscribe(<span class="keyword">new</span> Action1&lt;House&gt;() &#123;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(House house)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>

<h2 id="switchMap"><a href="#switchMap" class="headerlink" title="switchMap"></a>switchMap</h2><p>switchMap()和flatMap()很像，除了一点：每当源Observable发射一个新的数据项（Observable）时，它将取消订阅并停止监视之前那个数据项产生的Observable，并开始监视当前发射的这一个。(也不懂什么使用场景,只知道是只监听当前的事件,只要一发送,过去的事件不在监听,只管理现在的事件)</p>
<h2 id="scan"><a href="#scan" class="headerlink" title="scan"></a>scan</h2><p>scan()对一个序列的数据应用一个函数，并将这个函数的结果发射出去作为下个数据应用合格函数时的第一个参数使用.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Observable.just(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)</span><br><span class="line">        .scan(<span class="keyword">new</span> Func2&lt;Integer, Integer, Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Integer <span class="title">call</span><span class="params">(Integer integer, Integer integer2)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> integer + integer2;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;).subscribe(<span class="keyword">new</span> Action1&lt;Integer&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Integer integer)</span> </span>&#123;</span><br><span class="line">        System.out.print(integer+“ ”);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>输出结果是:1,3,6,10,15<br>1 = 1<br>3 = 1+2<br>6 = 3+3<br>10 = 6+4<br>15 = 10+5;<br>实现的函数是两个整数相加,第一个整数时,默认第0个数是0,后面进来一个数就和当前计算的结果相加;</p>
<h2 id="groupBy"><a href="#groupBy" class="headerlink" title="groupBy"></a>groupBy</h2><p>groupBy()将原始Observable发射的数据按照key来拆分成一些小的Observable，然后这些小Observable分别发射其所包含的的数据，和SQL中的groupBy类似。实际使用中，我们需要提供一个生成key的规则（也就是Func1中的call方法），所有key相同的数据会包含在同一个小的Observable中。另外我们还可以提供一个函数来对这些数据进行转化，有点类似于集成了flatMap。这只是在顺序上进行了调整,在观察者方收到数据的顺序是相同key的是临近的.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">List&lt;House&gt; houses = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">houses.add(<span class="keyword">new</span> House(<span class="string">"中粮·海景壹号"</span>, <span class="string">"中粮海景壹号新出大平层！总价4500W起"</span>));</span><br><span class="line">houses.add(<span class="keyword">new</span> House(<span class="string">"竹园新村"</span>, <span class="string">"满五唯一，黄金地段"</span>));</span><br><span class="line">houses.add(<span class="keyword">new</span> House(<span class="string">"中粮·海景壹号"</span>, <span class="string">"毗邻汤臣一品"</span>));</span><br><span class="line">houses.add(<span class="keyword">new</span> House(<span class="string">"竹园新村"</span>, <span class="string">"顶层户型，两室一厅"</span>));</span><br><span class="line">houses.add(<span class="keyword">new</span> House(<span class="string">"中粮·海景壹号"</span>, <span class="string">"南北通透，豪华五房"</span>));</span><br><span class="line">Observable&lt;GroupedObservable&lt;String, House&gt;&gt; groupByCommunityNameObservable = Observable.from(houses)</span><br><span class="line">        .groupBy(<span class="keyword">new</span> Func1&lt;House, String&gt;() &#123;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> String <span class="title">call</span><span class="params">(House house)</span> </span>&#123;</span><br><span class="line">            <span class="comment">//生成key的规则,根据communityName相同的分为一组;</span></span><br><span class="line">                <span class="keyword">return</span> house.communityName;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>

<p>执行结果:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">小区:中粮·海景壹号; 房源描述:中粮海景壹号新出大平层！总价4500W起</span><br><span class="line">小区:中粮·海景壹号; 房源描述:毗邻汤臣一品</span><br><span class="line">小区:中粮·海景壹号; 房源描述:南北通透，豪华五房</span><br><span class="line">小区:竹园新村; 房源描述:满五唯一，黄金地段</span><br><span class="line">小区:竹园新村; 房源描述:顶层户型，两室一厅</span><br></pre></td></tr></table></figure>

<h2 id="Filter"><a href="#Filter" class="headerlink" title="Filter"></a><strong>Filter</strong></h2><p><strong>filter(Func1)</strong>用来过滤观测序列中我们不想要的值，只返回满足条件的值</p>
<p>还是拿前面文章中的小区Community[] communities来举例，假设我需要赛选出所有房源数大于10个的小区，我们可以这样实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Observable.from(communities)</span><br><span class="line">        .filter(<span class="keyword">new</span> Func1&lt;Community, Boolean&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> Boolean <span class="title">call</span><span class="params">(Community community)</span> </span>&#123;</span><br><span class="line">                <span class="keyword">return</span> community.houses.size()&gt;<span class="number">10</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).subscribe(<span class="keyword">new</span> Action1&lt;Community&gt;() &#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Community community)</span> </span>&#123;</span><br><span class="line">        System.out.println(community.name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="take"><a href="#take" class="headerlink" title="take"></a>take</h2><p><strong>take(int)</strong>用一个整数n作为一个参数，从原始的序列中发射前n个元素</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Observable.from(communities)</span><br><span class="line">    .take(<span class="number">10</span>)</span><br><span class="line">    .subscribe(<span class="keyword">new</span> Action1&lt;Community&gt;() &#123;</span><br><span class="line">      <span class="meta">@Override</span></span><br><span class="line">      <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Community community)</span> </span>&#123;</span><br><span class="line">        System.out.println(community.name);</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;);</span><br></pre></td></tr></table></figure>

<p><strong>但是后面的数据怎么办?</strong></p>
<h2 id="takeLast"><a href="#takeLast" class="headerlink" title="takeLast"></a>takeLast</h2><p><strong>takeLast(int)</strong>同样用一个整数n作为参数，只不过它发射的是观测序列中后n个元素。</p>
<h2 id="takeUntil"><a href="#takeUntil" class="headerlink" title="takeUntil"></a>takeUntil</h2><p><strong>takeUntil(Observable)</strong>订阅并开始发射原始Observable，同时监视我们提供的第二个Observable。如果第二个Observable发射了一项数据或者发射了一个终止通知，takeUntil()返回的Observable会停止发射原始Observable并终止。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">Observable&lt;Long&gt; observableA = Observable.interval(<span class="number">300</span>, TimeUnit.MILLISECONDS);</span><br><span class="line">Observable&lt;Long&gt; observableB = Observable.interval(<span class="number">800</span>, TimeUnit.MILLISECONDS);</span><br><span class="line"></span><br><span class="line">observableA.takeUntil(observableB)</span><br><span class="line">        .subscribe(<span class="keyword">new</span> Subscriber&lt;Long&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onCompleted</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                System.exit(<span class="number">0</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(Throwable e)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onNext</span><span class="params">(Long aLong)</span> </span>&#123;</span><br><span class="line">                System.out.println(aLong);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    Thread.sleep(Integer.MAX_VALUE);</span><br><span class="line">&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">    e.printStackTrace();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>程序的输出:0,1</p>
<p><strong>takeUntil(Func1)</strong>还可以通过Func1中的call方法来判断是否需要终止发射数据。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Observable.just(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>)</span><br><span class="line">                .takeUntil(<span class="keyword">new</span> Func1&lt;Integer, Boolean&gt;() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> Boolean <span class="title">call</span><span class="params">(Integer integer)</span> </span>&#123;</span><br><span class="line">                        <span class="keyword">return</span> integer &gt;= <span class="number">5</span>;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;).subscribe(<span class="keyword">new</span> Action1&lt;Integer&gt;() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">call</span><span class="params">(Integer integer)</span> </span>&#123;</span><br><span class="line">                System.out.println(integer);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br></pre></td></tr></table></figure>

<p>输出结果:1,2,3,4</p>
<h1 id="线程调度"><a href="#线程调度" class="headerlink" title="线程调度"></a>线程调度</h1><p>异步是相对于主线程来讲的子线程操作，在这里我们不妨使用线程调度这个概念更加贴切。</p>
<p>Scheduler:调度器,用于线程控制</p>
<ul>
<li>Scheduler.immediate()  默认当前线程,不写就是这个,一般不写</li>
<li>Scheduler.newThread()  每次都创建新线程去执行,消耗大,不建议用</li>
<li>Scheduler.io()  IO密集型任务(eg:异步阻塞IO操作),默认是一个 CacheThreadScheduler,从线程池中去取一个线程,</li>
<li>Scheduler.computation() CPU密集计算线程,线程池中的线程数和CPU核心数一致,多用于处理图形界面大量的计算或者事件循环;</li>
<li>Scheduler.trampoline() 当其它排队的任务完成后,当前线程排队开始执行;</li>
<li>AndroidScheduler.mainThread() Android 的 UI 线程</li>
</ul>
<p>实际上线程调度只有subscribeOn（）和observeOn（）两个方法。对于初学者，只需要掌握两点：</p>
<ol>
<li>subscribeOn（）它指示Observable在一个指定的调度器上创建（只作用于被观察者创建阶段）。只能指定一次，如果指定多次则以第一次为准</li>
<li>observeOn（）指定在事件传递（加工变换）和最终被处理（观察者）的发生在哪一个调度器。可指定多次，每次指定完都在下一步生效。</li>
</ol>
<p>线程调度掌握到这个程度，在入门阶段时绝对够用的了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Observable.just(getFilePath())</span><br><span class="line">          <span class="comment">//指定在新线程中创建被观察者 Observable</span></span><br><span class="line">         .subscribeOn(Schedulers.newThread())</span><br><span class="line">     <span class="comment">//将接下来执行的线程环境指定为io线程,必须要先制定下面操作的线程,然后再指定操作;</span></span><br><span class="line">         .observeOn(Schedulers.io())</span><br><span class="line">           <span class="comment">//map就处在io线程</span></span><br><span class="line">         .map(mMapOperater)</span><br><span class="line">           <span class="comment">//将后面执行的线程环境切换为主线程，</span></span><br><span class="line">           <span class="comment">//但是这一句 observeOn 依然执行在io线程</span></span><br><span class="line">         .observeOn(AndroidSchedulers.mainThread())</span><br><span class="line">         <span class="comment">//指定线程无效，但这句代码本身执行在主线程,一个操作只能制定一个 subscribeOn,多了以第一个为准;</span></span><br><span class="line">         .subscribeOn(Schedulers.io())</span><br><span class="line">         <span class="comment">//执行在主线程</span></span><br><span class="line">         .subscribe(mSubscriber);</span><br></pre></td></tr></table></figure>



    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/03/31/完全背包问题/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/03/31/完全背包问题/" itemprop="url">完全背包问题</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-31T19:17:58+08:00">
                2017-03-31
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,560
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <h1 id="问题描述"><a href="#问题描述" class="headerlink" title="问题描述"></a>问题描述</h1><blockquote>
<p>有n种物品，每种物品有无限个，每个物品的重量为weight[i]，每个物品的价值为value[i]。 现在有一个背包，它所能容纳的重量为total，问：当你面对这么多有价值的物品时，你的背包所能带走的最大价值是多少？</p>
</blockquote>
<ul>
<li>n:物品数量</li>
<li>weight[] :每个物品的重量</li>
<li>value[]: 每个物品的价值</li>
<li>total:背包的最大承重</li>
</ul>
<h1 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h1><p>完全背包问题和之前的 <a href="https://zachaxy.github.io/2017/03/30/01%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/">01背包问题</a>思路是类似的,只不过完全背包问题中对每个物品的数量没有了限制,可以无限使用。这里直接使用最优解的方法做了，如果你对如何从普通解到最优解的转换还不熟悉，请参考 <a href="https://zachaxy.github.io/2017/03/30/01%E8%83%8C%E5%8C%85%E9%97%AE%E9%A2%98/">01背包问题</a>；</p>
<p>使用一个<code>dp[n][total+1]</code>数组,其中<code>dp[j]</code>表示在背包最大承重为j的情况下的最优解. 那么<code>dp[i][j]</code>的值如何确定呢?</p>
<p>首先:确定当前最大的承重是<code>j</code>,那么用不用物品<code>i</code>呢?</p>
<p>如果不使用<code>i</code>,那么<code>dp[i][j] = dp[i-1][j]</code></p>
<p>如果使用<code>i</code>,那么<code>dp[i][j] = dp[i][j-w[i]]+v[i]</code></p>
<h1 id="初步实现"><a href="#初步实现" class="headerlink" title="初步实现"></a>初步实现</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">  <span class="comment">//开始套路</span></span><br><span class="line">  <span class="keyword">int</span> n;  <span class="comment">//一共有n件物品</span></span><br><span class="line">  <span class="keyword">int</span> total; <span class="comment">//背包的总重量为total</span></span><br><span class="line"></span><br><span class="line">  n = <span class="number">5</span>;</span><br><span class="line">  total = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">int</span>[] w = &#123;<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">2</span>, <span class="number">2</span>&#125;;</span><br><span class="line">  <span class="keyword">int</span>[] v = &#123;<span class="number">6</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">3</span>, <span class="number">6</span>&#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">int</span>[][] dp = <span class="keyword">new</span> <span class="keyword">int</span>[n][total + <span class="number">1</span>];</span><br><span class="line"></span><br><span class="line">  <span class="comment">//初始化第一行</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = w[<span class="number">0</span>]; i &lt; total + <span class="number">1</span>; i++) &#123;</span><br><span class="line">    dp[<span class="number">0</span>][i] = dp[<span class="number">0</span>][i - w[<span class="number">0</span>]] + v[<span class="number">0</span>];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//第一列就不初始化了吧</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; total + <span class="number">1</span>; j++) &#123;</span><br><span class="line">      dp[i][j] = dp[i - <span class="number">1</span>][j];</span><br><span class="line">      <span class="keyword">if</span> (j &gt;= w[i]) &#123;</span><br><span class="line">        dp[i][j] = Math.max(dp[i][j], dp[i][j - w[i] + v[i]]);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  System.out.println(dp[n-<span class="number">1</span>][total]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="压缩空间"><a href="#压缩空间" class="headerlink" title="压缩空间"></a>压缩空间</h1><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//开始套路</span></span><br><span class="line">    <span class="keyword">int</span> n;  <span class="comment">//一共有n件物品</span></span><br><span class="line">    <span class="keyword">int</span> total; <span class="comment">//背包的总重量为total</span></span><br><span class="line"></span><br><span class="line">    n = <span class="number">5</span>;</span><br><span class="line">    total = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span>[] w = &#123;<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">2</span>, <span class="number">2</span>&#125;;</span><br><span class="line">    <span class="keyword">int</span>[] v = &#123;<span class="number">6</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">3</span>, <span class="number">6</span>&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span>[] dp = <span class="keyword">new</span> <span class="keyword">int</span>[total + <span class="number">1</span>];</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化第一行</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = w[<span class="number">0</span>]; i &lt; total + <span class="number">1</span>; i++) &#123;</span><br><span class="line">        dp[i] = dp[i - w[<span class="number">0</span>]] + v[<span class="number">0</span>];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; total + <span class="number">1</span>; j++) &#123;</span><br><span class="line">            <span class="keyword">if</span> (j &gt;= w[i]) &#123;</span><br><span class="line">                dp[j] = Math.max(dp[j], dp[j - w[i] + v[i]]);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(dp[total]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其实这里面的初始化第一行不是必须的,直接进行下面的<code>for</code>循环也是可以的,只需要把外层<code>for</code>的初始值改为<code>0</code>即可;我这里只不过是习惯了写动态规划的套路,在这样做的,如果你喜欢更简洁的写法,请看下面.</p>
<h1 id="更简洁的写法"><a href="#更简洁的写法" class="headerlink" title="更简洁的写法"></a>更简洁的写法</h1><p>改进后的代码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">f3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">//开始套路</span></span><br><span class="line">    <span class="keyword">int</span> n;  <span class="comment">//一共有n件物品</span></span><br><span class="line">    <span class="keyword">int</span> total; <span class="comment">//背包的总重量为total</span></span><br><span class="line"></span><br><span class="line">    n = <span class="number">5</span>;</span><br><span class="line">    total = <span class="number">10</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span>[] w = &#123;<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>, <span class="number">2</span>, <span class="number">2</span>&#125;;</span><br><span class="line">    <span class="keyword">int</span>[] v = &#123;<span class="number">6</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">3</span>, <span class="number">6</span>&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span>[] dp = <span class="keyword">new</span> <span class="keyword">int</span>[total + <span class="number">1</span>];</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = w[i]; j &lt; total + <span class="number">1</span>; j++) &#123;</span><br><span class="line">            dp[j] = Math.max(dp[j], dp[j - w[i] + v[i]]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    System.out.println(dp[total]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="完全背包问题的变形问题"><a href="#完全背包问题的变形问题" class="headerlink" title="完全背包问题的变形问题"></a>完全背包问题的变形问题</h1><h2 id="最小钱币数"><a href="#最小钱币数" class="headerlink" title="最小钱币数"></a>最小钱币数</h2><blockquote>
<p> 给定一个数组arr,该数组中的各个数代表钱币的面值,每个面值的数量无限多, 给定一个aim,用arr中的钱币凑齐aim数,是的凑出的钱币数量最少</p>
</blockquote>
<p>直接上代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">minCoins1</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (arr == <span class="keyword">null</span> || arr.length == <span class="number">0</span> || aim &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> n = arr.length;</span><br><span class="line">    <span class="keyword">int</span> max = Integer.MAX_VALUE;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//(1)构造动态数组 (2)此时的数组其实已经初始化为全0了;</span></span><br><span class="line">    <span class="keyword">int</span>[][] dp = <span class="keyword">new</span> <span class="keyword">int</span>[n][aim + <span class="number">1</span>];  <span class="comment">//n行,aim+1列;此时的列的索引就是当前凑的货币总额;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//(2)初始化第一行;</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= aim; j++) &#123;  <span class="comment">//此时j就是当前行的钱币凑成的总额;注意是从1开始的,也就是说第0列的值为0;</span></span><br><span class="line">        dp[<span class="number">0</span>][j] = max;<span class="comment">//先赋值为max;</span></span><br><span class="line">        <span class="comment">//第一个判定条件是保证第二个判定条件数组下标不越界</span></span><br><span class="line">        <span class="comment">//只是初始化第一行,将arr[0]的倍数列初始化响应的倍数;</span></span><br><span class="line">        <span class="keyword">if</span> (j - arr[<span class="number">0</span>] &gt;= <span class="number">0</span> &amp;&amp; dp[<span class="number">0</span>][j - arr[<span class="number">0</span>]] != max) &#123;</span><br><span class="line">            dp[<span class="number">0</span>][j] = dp[<span class="number">0</span>][j - arr[<span class="number">0</span>]] + <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span> left = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123;<span class="comment">//最外层按列遍历</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= aim; j++) &#123;<span class="comment">//内层按行遍历</span></span><br><span class="line">            left = max;</span><br><span class="line">            <span class="comment">//判断j是不是&gt;arr[i],并且第j-arr[i]列不是max</span></span><br><span class="line">            <span class="keyword">if</span> (j - arr[i] &gt;= <span class="number">0</span> &amp;&amp; dp[i][j - arr[i]] != max) &#123;</span><br><span class="line">                left = dp[i][j - arr[i]] + <span class="number">1</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//这一步,比较left和上一行的大小才进行真正的数组初始化;</span></span><br><span class="line">            dp[i][j] = Math.min(left, dp[i - <span class="number">1</span>][j]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> dp[n - <span class="number">1</span>][aim] != max ? dp[n - <span class="number">1</span>][aim] : -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>压缩空间的方法:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//最简洁的写法;</span></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">f1</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">     <span class="comment">//创建数组</span></span><br><span class="line">     <span class="keyword">int</span>[] dp = <span class="keyword">new</span> <span class="keyword">int</span>[aim + <span class="number">1</span>];</span><br><span class="line"> </span><br><span class="line">     <span class="comment">//初始化第一行</span></span><br><span class="line">     <span class="keyword">int</span> max = Integer.MAX_VALUE;</span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; aim + <span class="number">1</span>; i++) &#123;</span><br><span class="line">         dp[i] = max;</span><br><span class="line">         <span class="keyword">if</span> (i &gt;= arr[<span class="number">0</span>] &amp;&amp; dp[i - arr[<span class="number">0</span>]] != max) &#123;</span><br><span class="line">             dp[i] = dp[i - arr[<span class="number">0</span>]] + <span class="number">1</span>;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"> </span><br><span class="line">     <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">         <span class="keyword">for</span> (<span class="keyword">int</span> j = arr[i]; j &lt; aim + <span class="number">1</span>; j++) &#123;</span><br><span class="line">             <span class="keyword">if</span> (dp[j - arr[i]] != max) &#123;</span><br><span class="line">                 dp[j] = Math.min(dp[j], dp[j - arr[i]] + <span class="number">1</span>);</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">return</span> dp[aim] != max ? dp[aim] : -<span class="number">1</span>;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>

<h2 id="换钱币的方法数"><a href="#换钱币的方法数" class="headerlink" title="换钱币的方法数"></a>换钱币的方法数</h2><blockquote>
<p>上一题是求最少钱币的数量,现在是让求有几种可以换算的方法(每种钱币数量无限)之前我们所有的动态规划目标都是一个:求最优解,现在让求的是所有的解的个数</p>
</blockquote>
<p><strong>直接上代码</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">f1</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span>[] dp = <span class="keyword">new</span> <span class="keyword">int</span>[aim + <span class="number">1</span>];</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化第一行</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; aim + <span class="number">1</span>; i += arr[<span class="number">0</span>]) &#123;</span><br><span class="line">        dp[i] = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; arr.length; i++) &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = arr[i]; j &lt; aim+<span class="number">1</span>; j++) &#123;</span><br><span class="line">            dp[j] += dp[j - arr[i]];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> dp[aim];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里需要注意的点是:需要把第0列初始化为1,而不是0;</p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/03/30/hexo搭建博客过程全纪录/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/03/30/hexo搭建博客过程全纪录/" itemprop="url">hexo搭建博客过程全纪录</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-30T17:30:53+08:00">
                2017-03-30
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,709
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <h1 id="准备工作"><a href="#准备工作" class="headerlink" title="准备工作"></a>准备工作</h1><ol>
<li><p>安装<a href="https://nodejs.org/en/download/" target="_blank" rel="noopener">Node.js</a>一路next即可</p>
</li>
<li><p>安装<a href="http://git-scm.com/download/" target="_blank" rel="noopener">git</a>,一路next即可</p>
</li>
<li><p>注册github账号,这个步骤就不说了吧…</p>
</li>
<li><p>生成ssh key(这一步非必须)</p>
<ol>
<li><p>检测之前是否有生成过ssh没</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cd  ~/.ssh   //注意 ~/.ssh之间没有空格</span><br></pre></td></tr></table></figure>

<p>如果提示：<code>No such file or directory</code> 说明你还未生成<code>ssh key</code></p>
</li>
<li><p>生成新的ssh key</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$ ssh-keygen -t rsa -C &quot;邮件地址@youremail.com&quot;  //这个邮箱地址就是你注册github使用的邮箱</span><br><span class="line">Generating public/private rsa key pair.</span><br><span class="line">Enter file in which to save the key (/c/Users/xxx/.ssh/id_rsa):</span><br></pre></td></tr></table></figure>

<p>第三行是在询问你将生成的ssh key放在哪里默认是你的用户目录,这里直接回车就好</p>
</li>
<li><p>接下来或让你创建一个密码,并再次确认</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Created directory &apos;/c/Users/zhangxin/.ssh&apos;.</span><br><span class="line">Enter passphrase (empty for no passphrase):</span><br><span class="line">Enter same passphrase again:</span><br></pre></td></tr></table></figure>
</li>
<li><p>添加 ssh key 到 github</p>
<p>打开本地<code>/c/Users/zhangxin/.ssh</code>,你的肯定不是我这个文件,改成你在是第二步保存的文件位置,将<code>id_rsa.pub</code>文件用记事本打开,将此文件里面内容为刚才生成人密钥。如果看不到这个文件，你需要设置显示隐藏文件。复制这个文件的内容,登陆你的github,点击右上角头像处的下拉列表 <code>Settings—&gt;SSH and GPG keys —&gt; 右上角 New SSH key</code>,把你本地生成的密钥复制到里面（key文本框中）， 点击<code>add key</code>就 ok 了.同时你也可以设置title用来为这个 key 做一个标示,因为我们很可能在多台电脑上都写博客并推送,不同的电脑需要按照相同的步骤,当然生成的ssh key是不同的,如果你需要同时在另一台电脑上工作,就需要把另一台电脑的ssh key 也添加到你的github中,title所以,你自己可以区分开就好,比如单位的,用一个<code>work</code>,在家的用一个<code>home</code>,随你喜欢.</p>
</li>
<li><p>测试 ssh 是否正确设置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">$ ssh -T git@github.com</span><br><span class="line"></span><br><span class="line">The authenticity of host &apos;github.com (207.97.227.239)&apos; can&apos;t be established.</span><br><span class="line">RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.</span><br><span class="line">Are you sure you want to continue connecting (yes/no)?</span><br><span class="line"></span><br><span class="line">//这一步输入yes</span><br><span class="line"></span><br><span class="line">	</span><br><span class="line">Hi cnfeat! You&apos;ve successfully authenticated, but GitHub does not provide shell access.</span><br></pre></td></tr></table></figure>

<p>如果正常的话,就是显示这些内容了.</p>
</li>
</ol>
</li>
<li><p>设置用户信息</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ git config --global user.name &quot;userName&quot;             //你的用户名,要加双引号的啊</span><br><span class="line">$ git config --global user.email  &quot;userName@xxx.com&quot;  //填写自己的邮箱 ,也要加双引号的啊</span><br></pre></td></tr></table></figure>

<p>查看用户设置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$ git config --list</span><br></pre></td></tr></table></figure>

<p>​</p>
</li>
</ol>
<h1 id="建立博客"><a href="#建立博客" class="headerlink" title="建立博客"></a>建立博客</h1><ol>
<li><p>登陆 github ,创建一个新的仓库,名字叫做 <code>xxx.github.io</code>,这里xxx要换成你的 github 的用户名,点击「Create Repository」 完成创建。</p>
</li>
<li><p>创建一个文件夹来保存你写的博客,例如在 E 盘下创建文件夹 <code>blogs</code></p>
</li>
<li><p>进入该文件夹,鼠标右键,打开<code>git bash</code></p>
</li>
<li><p>安装<code>hexo</code>,在bash中输入<code>npm install -g hexo</code></p>
</li>
<li><p><code>bash</code>中进入<code>bolgs</code>文件夹下,<code>cd E:/blogs</code></p>
</li>
<li><p>输入<code>hexo init</code></p>
</li>
<li><p>现在已经搭建起来一个本地博客了 , 输入以下命令验证</p>
<p><code>$ hexo g</code> -生成</p>
<p><code>$ hexo s</code> -启动服务本地预览 </p>
<p>然后到浏览器输入localhost:4000进行预览(ctrl + c 停止本地预览)</p>
<p>​</p>
<p>​</p>
</li>
</ol>
<h1 id="更换主题"><a href="#更换主题" class="headerlink" title="更换主题"></a>更换主题</h1><p>   目前使用的是<code>hexo</code>默认的主题,其实也很好看的,如果你不喜欢,可以更换主题,这里推荐<code>jacman</code>,</p>
<ol>
<li><p>下载主题</p>
<p>将主题下载到<code>blogs/theme</code>目录下在<code>bash</code>中执行<code>git clone https://github.com/wuchong/jacman.git E:/blogs/themes/jacman</code></p>
</li>
<li><p>更换主题</p>
<p>修改<code>blogs</code>目录下的config.yml配置文件中的theme属性，将其设置为jacman</p>
</li>
<li><p>启用主题</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">hexo clean --因为主题换了 你需要clean以下老主题生成的缓存</span><br><span class="line">cd themes/jacman</span><br><span class="line">git pull</span><br><span class="line">hexo g   --生成</span><br><span class="line">hexo s   --启动本地预览</span><br></pre></td></tr></table></figure>

<p>​</p>
</li>
</ol>
<h1 id="上传博客"><a href="#上传博客" class="headerlink" title="上传博客"></a>上传博客</h1><p>经过上面的步骤之后,就可以开始写博客并上传到github上了,步骤如下:</p>
<ol>
<li>进入到<code>blogs</code>文件加下,运行<code>hexo n &quot;博客文件名&quot;</code></li>
<li>找到<code>blogs/source/_posts/xxx</code>其中xxx是第一步新键的博客文件名,默认为<code>.md文件</code></li>
<li>打开该文件,书写博客,保存</li>
<li><code>执行 ./ok.sh</code>,中间可能会遇到让你输入用户名和密码的情况,输入即可.（关于ok.sh，请看下面的快捷部署）</li>
</ol>
<h1 id="快捷部署"><a href="#快捷部署" class="headerlink" title="快捷部署"></a>快捷部署</h1><ol>
<li><p>进入之前创建的 blogs 的根目录 接着操作以下命令</p>
<p><code>$ cd blogs</code></p>
<p>注意 1：现在我们需要clone我们自己的GitHub仓库了</p>
<p>注意 2：切记下面是<strong>你自己的仓库名</strong> , 把名字都改过来 , 下面我用的是我的仓库名字</p>
<p><code>$ git clone https://github.com/zachaxy/zachaxy.github.io.git .deploy/zachaxy.github.io</code></p>
<p>翻译下这条命令的意思</p>
<p>将我们之前创建的GitHub 仓库克隆到本地 , 命令会新建一个目录叫做.deploy用于存放克隆的代码。</p>
<p>然后会在.deploy文件夹下生成一个 <strong>你的名字.github.io</strong> 的文件夹用于存放文件</p>
</li>
<li><p>接着在 Hexo <strong>根目录</strong>下创建一个 .txt 文件 , 把下面的命令复制进去</p>
</li>
<li><p>注意 ：<strong>你的GitHub名字</strong>是什么就<strong>把你的名字全部改到下面</strong> , 细心点。稍微解释一下下面的命令，在部署文章之前，我们肯定已经使用 <code>hexo n &quot;xxx&quot;</code>产生了一个xxx.md的文件，并书写完博客了，那么接下来这个第一行就是生成博客对应的html文件等，这些文件都放在 <code>hexo/public</code> 路径下；第二条指令是将 <code>public</code> 下的所有文件 拷贝到 本地的<code>.deploy/zachaxy.github.io</code> 路径下（相同文件会覆盖）；第三条指令，进入<code>.deploy/zachaxy.github.io</code>路径；接下来第四条到第六条指令，就是普通的提交命令，不在解释。</p>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">hexo generate</span><br><span class="line">cp -R public/* .deploy/zachaxy.github.io</span><br><span class="line">cd .deploy/zachaxy.github.io</span><br><span class="line">git add .</span><br><span class="line">git commit -m  &quot;update&quot;</span><br><span class="line">git push origin master</span><br></pre></td></tr></table></figure>

<ol start="4">
<li>将这个 <strong>.txt 文件的后缀改成 .sh</strong> , 它就变成了脚本文件 , 我们就将文件改成 <strong>ok.sh</strong> 。</li>
<li>从此以后需要部署本地博客到 GitHub , 在 hexo 根目录下，直接<code>./ok.sh</code> , 会弹出提示 , 需要输入 GitHub 的用户名跟密码 , 按提示输入自己的用户名和密码即可</li>
</ol>
<h1 id="jacman配置"><a href="#jacman配置" class="headerlink" title="jacman配置"></a>jacman配置</h1><p><a href="https://smartbeng.github.io/2017/03/26/blogFinish/" target="_blank" rel="noopener">最适合新手的 GitHub + Hexo 「大话」博客搭建教程</a></p>
<p><a href="http://whatbeg.com/2017/04/13/hexosomeopt.html" target="_blank" rel="noopener">Hexo新的一些优化</a></p>
<p> <a href="http://kubicode.me/2016/03/18/Hexo/The-Trick-about-Hexo-Support-MutliLine-Equation-using-Mathjax/" target="_blank" rel="noopener">[小技巧]让Hexo在使用Mathjax时支持多行公式</a></p>
<p><a href="http://kubicode.me/2016/03/16/Hexo/Fix-Hexo-Bug-In-Mathjax/" target="_blank" rel="noopener">修复Hexo写Mathjax公式多个下标失效的问题</a></p>
<p><a href="http://www.jianshu.com/p/6c1196f12302" target="_blank" rel="noopener">用 Hexo 搭建个人博客-02：进阶试验</a></p>
<p> <a href="http://whatbeg.com/2016/09/17/hexo-migrate.html" target="_blank" rel="noopener">Hexo部署环境迁移–多台电脑搭建Hexo环境</a></p>
<p> <a href="http://lowrank.science/Hexo-Migration/" target="_blank" rel="noopener">多机更新 Hexo 博客</a></p>




    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>











  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">



  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zachaxy.github.io/2017/03/30/01背包问题/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zachaxy">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zachaxy">
    </span>


      <header class="post-header">



          <h2 class="post-title" itemprop="name headline">

                <a class="post-title-link" href="/2017/03/30/01背包问题/" itemprop="url">01背包问题</a></h2>


        <div class="post-meta">
          <span class="post-time">

              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>

                <span class="post-meta-item-text">发表于</span>

              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-30T17:25:18+08:00">
                2017-03-30
              </time>





          </span>













            <div class="post-wordcount">


                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>

                  <span class="post-meta-item-text">字数统计&#58;</span>

                <span title="字数统计">
                  1,633
                </span>





            </div>




        </div>
      </header>





    <div class="post-body" itemprop="articleBody">







            <h1 id="01背包问题"><a href="#01背包问题" class="headerlink" title="01背包问题"></a>01背包问题</h1><blockquote>
<p>有n个物品，每个物品的重量为weight[i]，每个物品的价值为value[i]。现在有一个背包，它所能容纳的重量为total，问：当你面对这么多有价值的物品时，你的背包所能带走的最大价值是多少？</p>
</blockquote>
<ul>
<li>n:物品数量</li>
<li>weight[] :每个物品的重量</li>
<li>value[]: 每个物品的价值</li>
<li>total:背包的最大承重</li>
</ul>
<h2 id="实现原理"><a href="#实现原理" class="headerlink" title="实现原理"></a>实现原理</h2><p>使用一个<code>dp[n + 1][weight + 1]</code>数组,其中<code>dp[i][j]</code>表示如果背包重量是<code>j</code>的情况下,使用前<code>i</code>个物品的最优解,</p>
<p>那么<code>dp[i][j]</code>的值如何确定呢?</p>
<p>首先:确定当前最大的承重是<code>j</code>,那么用不用物品<code>i</code>呢?</p>
<p>如果使用,<code>dp[i][j] = dp[i-1][j-w[i]]+v[i]</code></p>
<p>如果不使用<code>i</code>,那么<code>dp[i][j] = dp[i-1][j]</code></p>
<p>所以<code>dp[i][j]</code>的值就是上述两者的最大值;</p>
<h2 id="初步实现"><a href="#初步实现" class="headerlink" title="初步实现"></a>初步实现</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f1</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">  Scanner in = <span class="keyword">new</span> Scanner(System.in);  </span><br><span class="line">  <span class="keyword">while</span> (in.hasNext()) &#123;  </span><br><span class="line">    <span class="keyword">int</span> n = in.nextInt();  <span class="comment">//背包数量;</span></span><br><span class="line">    <span class="keyword">int</span> weight = in.nextInt();  <span class="comment">//重量;</span></span><br><span class="line">    <span class="keyword">int</span>[] v = <span class="keyword">new</span> <span class="keyword">int</span>[n + <span class="number">1</span>];  <span class="comment">//value;</span></span><br><span class="line">    <span class="keyword">int</span>[] w = <span class="keyword">new</span> <span class="keyword">int</span>[n + <span class="number">1</span>];  <span class="comment">//weight;</span></span><br><span class="line"><span class="comment">//我们这里都是用了一个+1的操作,就是说不从0开始计算了,而是从1开始计算,这样更容易理解吧;</span></span><br><span class="line">    <span class="keyword">int</span>[][] res = <span class="keyword">new</span> <span class="keyword">int</span>[n + <span class="number">1</span>][weight + <span class="number">1</span>];  <span class="comment">//结果集;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;=n; i++) &#123;  </span><br><span class="line">      w[i] = in.nextInt();  </span><br><span class="line">      v[i] = in.nextInt();  </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//初始化第一列</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;=n; i++) &#123;  </span><br><span class="line">      res[i][<span class="number">0</span>] = <span class="number">0</span>;  </span><br><span class="line">    &#125; </span><br><span class="line">    </span><br><span class="line">    <span class="comment">//初始化第一行;</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt;=weight; j++) &#123;  </span><br><span class="line">      res[<span class="number">0</span>][j] = <span class="number">0</span>;  </span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">	<span class="comment">//开始规划</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++) &#123;  </span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= weight; j++) &#123;  <span class="comment">//这里k代表的是当前背包的重量;</span></span><br><span class="line">        res[i][j] = res[i - <span class="number">1</span>][j];    <span class="comment">//不用当前j</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (j &gt;= w[i]) &#123;  <span class="comment">//当前包的重量小于j,考虑很周到,如果当前包重量过大,也是不行的...</span></span><br><span class="line">          <span class="keyword">if</span> (res[i-<span class="number">1</span>][j - w[i]] + v[i] &gt; res[i-<span class="number">1</span>][j])  <span class="comment">//用当前i比不用更大,那么就用上;</span></span><br><span class="line">          &#123;  </span><br><span class="line">            res[i][j] = res[i-<span class="number">1</span>][j - w[i]] + v[i];    <span class="comment">//使用当前i;</span></span><br><span class="line">          &#125;     </span><br><span class="line">        &#125;  </span><br><span class="line">      &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">    System.out.println(res[n][weight]);  </span><br><span class="line">  &#125;  </span><br><span class="line">  in.close();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="压缩空间"><a href="#压缩空间" class="headerlink" title="压缩空间"></a>压缩空间</h2><p>上面的实现方法用了一个二维数组,其实完全可以用一个一维数组来代替;</p>
<blockquote>
<p>这里有一个要注意的地方:编程思路和上面是一样的,也是两层循环,只不过现在从二维变成了一维,可是我们需要<code>dp[i][j] = dp[i-1][j-w[i]]+v[i]</code>的情况,如果内层循环也是从1开始计数的话,前面的值就被覆盖了,后面的值依赖前面的值,所以内层循环从右到左开始循环;</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">f2</span><span class="params">()</span> </span>&#123;  </span><br><span class="line">  Scanner in = <span class="keyword">new</span> Scanner(System.in);  </span><br><span class="line">  <span class="keyword">while</span> (in.hasNext()) &#123;  </span><br><span class="line">    <span class="keyword">int</span> n = in.nextInt();  <span class="comment">//背包数量</span></span><br><span class="line">    <span class="keyword">int</span> weight = in.nextInt();  <span class="comment">//背包承重</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">int</span>[] v = <span class="keyword">new</span> <span class="keyword">int</span>[n + <span class="number">1</span>];  <span class="comment">//values;</span></span><br><span class="line">    <span class="keyword">int</span>[] w = <span class="keyword">new</span> <span class="keyword">int</span>[n + <span class="number">1</span>];  <span class="comment">//weights;</span></span><br><span class="line">    <span class="keyword">int</span>[] res = <span class="keyword">new</span> <span class="keyword">int</span>[weight + <span class="number">1</span>];  <span class="comment">//结果集</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;=n; i++) &#123;  </span><br><span class="line">      w[i] = in.nextInt();  </span><br><span class="line">      v[i] = in.nextInt();  </span><br><span class="line">    &#125;  </span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">1</span>;i&lt;=n;i++) &#123;  </span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">int</span> k = weight; k&gt;=<span class="number">0</span>; k--) &#123;  </span><br><span class="line">        <span class="keyword">if</span> (w[i] &lt;= k) &#123;  </span><br><span class="line">          <span class="keyword">if</span> (v[i] + res[k - w[i]] &gt; res[k])  </span><br><span class="line">          &#123;  </span><br><span class="line">            res[k] = v[i] + res[k - w[i]];  </span><br><span class="line">          &#125;  </span><br><span class="line"></span><br><span class="line">        &#125;  </span><br><span class="line">      &#125;  </span><br><span class="line">    &#125;  </span><br><span class="line">    System.out.println(res[weight]);  </span><br><span class="line">  &#125;  </span><br><span class="line">  in.close();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="一个更简洁的写法"><a href="#一个更简洁的写法" class="headerlink" title="一个更简洁的写法"></a>一个更简洁的写法</h2><p>  注意传入进来的v和w是从0开始的,不是从1开始的了;上面使用的从1开始只是为了方便的说明问题,现在v和w都是从0开始的,只是res结果集还是使用的<code>total+1</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">f3</span><span class="params">(<span class="keyword">int</span>[] values, <span class="keyword">int</span>[] weights, <span class="keyword">int</span> maxWeight)</span> </span>&#123;</span><br><span class="line"> </span><br><span class="line">  <span class="keyword">int</span>[] res = <span class="keyword">new</span> <span class="keyword">int</span>[maxWeight + <span class="number">1</span>];  <span class="comment">//动态规划数组;</span></span><br><span class="line">  </span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;  <span class="comment">//遍历到第i个物品;</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = maxWeight; j &gt;= weights[i]; j--) &#123;  <span class="comment">//内层循环倒着来;注意人家的终止条件啊;</span></span><br><span class="line">      <span class="keyword">int</span> takeValue = values[i] + res[j - weights[i]];  <span class="comment">//使用当前i</span></span><br><span class="line">      <span class="keyword">if</span> (takeValue &gt; res[j]) &#123;  <span class="comment">//使用当前i的时候如果比不使用的时候大,那么将res[j]的位置替换成使用的情况;</span></span><br><span class="line">        res[j] = takeValue;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">return</span> res[ans.length - <span class="number">1</span>];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="01背包的一个变形问题"><a href="#01背包的一个变形问题" class="headerlink" title="01背包的一个变形问题"></a>01背包的一个变形问题</h2><blockquote>
<p>给定一个物品数组,每个物品都有一个价值,每个物品数量为1,再得定一个整数aim代表期望的价值,求组成aim的最小物品数量,如果组不成,那么返回-1;</p>
</blockquote>
<p><strong>使用二维数组的做法</strong></p>
<p><code>dp[i][j]</code>代表的是<code>aim=j</code>的情况下,使用前面<code>i</code>种钱币的最优解;那么在接下来的规划中如何做呢?</p>
<p>首先我们是把数组中的每个元素都初始化为<code>Integer.MAX_VALUE</code>了,那么<code>j</code>的情况下,考虑能不能使用<code>i</code>,如果<code>dp[i-1][j-v[i]]</code>不是最大值,那么就可以用上<code>j</code>,否则赋值为<code>dp[i-1][j]</code>;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">int</span> <span class="title">f4</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (arr == <span class="keyword">null</span> || arr.length == <span class="number">0</span> || aim &lt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">int</span> n = arr.length;</span><br><span class="line">  <span class="keyword">int</span> max = Integer.MAX_VALUE;</span><br><span class="line">  <span class="keyword">int</span>[][] dp = <span class="keyword">new</span> <span class="keyword">int</span>[n][aim + <span class="number">1</span>]; <span class="comment">//创建dp数组</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">//和之前一样,初始化数组的第一行</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= aim; j++) &#123;</span><br><span class="line">    dp[<span class="number">0</span>][j] = max;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">//只给恰好等于的元素置为1;</span></span><br><span class="line">  <span class="keyword">if</span> (arr[<span class="number">0</span>] &lt;= aim) &#123;</span><br><span class="line">    dp[<span class="number">0</span>][arr[<span class="number">0</span>]] = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">int</span> leftup = <span class="number">0</span>; <span class="comment">// 左上角某个位置的值</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123; <span class="comment">//最外层从上到下遍历</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= aim; j++) &#123; <span class="comment">//最内层从左到右遍历</span></span><br><span class="line">      leftup = max;</span><br><span class="line">      <span class="keyword">if</span> (j - arr[i] &gt;= <span class="number">0</span> &amp;&amp; dp[i - <span class="number">1</span>][j - arr[i]] != max) &#123; <span class="comment">//现在是上一行的,有值才赋值=&gt;保证只使用一次;</span></span><br><span class="line">        leftup = dp[i - <span class="number">1</span>][j - arr[i]] + <span class="number">1</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      dp[i][j] = Math.min(leftup, dp[i - <span class="number">1</span>][j]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> dp[n - <span class="number">1</span>][aim] != max ? dp[n - <span class="number">1</span>][aim] : -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>使用一维数组的做法</strong></p>
<p>注意内层循环依然使用从右到左的方式;</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">f5</span><span class="params">(<span class="keyword">int</span>[] arr, <span class="keyword">int</span> aim)</span> </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (arr == <span class="keyword">null</span> || arr.length == <span class="number">0</span> || aim &lt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> -<span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">int</span> n = arr.length;</span><br><span class="line">  <span class="keyword">int</span> max = Integer.MAX_VALUE;</span><br><span class="line">  <span class="keyword">int</span>[] dp = <span class="keyword">new</span> <span class="keyword">int</span>[aim + <span class="number">1</span>];</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= aim; j++) &#123;</span><br><span class="line">    dp[j] = max;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (arr[<span class="number">0</span>] &lt;= aim) &#123;</span><br><span class="line">    dp[arr[<span class="number">0</span>]] = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">int</span> leftup = <span class="number">0</span>; <span class="comment">// 左上角某个位置的值</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> j = aim; j &gt; <span class="number">0</span>; j--) &#123;</span><br><span class="line">      leftup = max;</span><br><span class="line">      <span class="comment">// if (j - arr[i] &gt;= 0 &amp;&amp; dp[i][j - arr[i]] != max) //之前是只要 a[i][j-cur]上有值就赋值</span></span><br><span class="line">      <span class="keyword">if</span> (j - arr[i] &gt;= <span class="number">0</span> &amp;&amp; dp[j - arr[i]] != max) &#123;</span><br><span class="line">        leftup = dp[j - arr[i]] + <span class="number">1</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      dp[j] = Math.min(leftup, dp[j]);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> dp[aim] != max ? dp[aim] : -<span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





    </div>










    <footer class="post-footer">








        <div class="post-eof"></div>

    </footer>
  </div>



  </article>



  </section>


  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/12/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/12/">12</a><span class="page-number current">13</span>
  </nav>



          </div>





        </div>



  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">

      <div id="sidebar-dimmer"></div>

    <div class="sidebar-inner">





      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">

              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="zachaxy">

              <p class="site-author-name" itemprop="name">zachaxy</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">


              <div class="site-state-item site-state-posts">

                <a href="/archives">

                  <span class="site-state-item-count">64</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>







              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>


          </nav>



          <div class="links-of-author motion-element">


                <span class="links-of-author-item">
                  <a href="https://github.com/zachaxy" target="_blank" title="GitHub">

                      <i class="fa fa-fw fa-globe"></i>GitHub</a>
                </span>

                <span class="links-of-author-item">
                  <a href="https://weibo.com/3242765540" target="_blank" title="Weibo">

                      <i class="fa fa-fw fa-globe"></i>Weibo</a>
                </span>


          </div>









        </div>
      </section>





    </div>
  </aside>



      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zachaxy</span>


    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>

      <span class="post-meta-item-text">站点文章字数总计&#58;</span>

    <span title="站点文章字数总计">147.9k</span>

</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>













      </div>
    </footer>


      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>

          <span id="scrollpercent"><span>0</span>%</span>

      </div>




  </div>



<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>
























    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>




    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>




    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>




    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>






  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>











  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>







































  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>

















  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>





</body>
</html>
